import {
	$loading,
	$msg
} from "./msg"
import {
	API as $API,
	BASE_URL as baseURL
} from './api'
import $CACHE from './cache'
import {
	getAppId
} from "@/common"

const http = function(config) {
	let {
		method
	} = config
	const token = uni.getStorageSync('token')
	//const token ="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTMzNywibmlja05hbWUiOiLpmYjnkZ7mnbAiLCJ1c2VybmFtZSI6IiIsImhlYWRlckltZyI6Imh0dHBzOi8vdGhpcmR3eC5xbG9nby5jbi9tbW9wZW4vdmlfMzIvUTBqNFR3R1RmVEpvNENpYlBXWU1hNklhVk1WeHBrelczbnJTa3hnZUdnaWF6MlBEVnZ2a1VBT3dHSnE2eDJJWTZhd3kwR1Q0V2gycXZZSlN5UVR4cjVlQS8xMzIiLCJ0eXBlIjoidXNlciIsIm1vYmlsZSI6IiIsInJvbGUiOiIxIiwibWFuYWdlcklkIjowLCJleHAiOjE3MzQ2MDk2NTYsImlhdCI6MTczNDA4NDA1NiwiaXNzIjoiaW5mb3JtYXRpb24ifQ.V3zGBKHhK5uaTc5hwe9QJrqoqsanxNBM_RxlMR14e9A"
	let {
		cache = false,
			header = {
				["Content-Type"]: "application/json",
				['token']: token
			},
	} = config;
	if ({}.toString.call(config.url).slice(8, -1) == "Array") {
		let urls = config.url;
		let urlType = urls.shift();
		config.url = (config.baseURL || baseURL) + ($API[urlType] || `/${urlType}/`) + urls.join('/');
	} else {
		config.url = (config.baseURL || baseURL) + ($API[config.url] || `/${config.url}`);
		//console.log(config, 'config')
		if (config.data && config.data.isLast) {
			config.url += config.data.id
		}
	}
	config.header = header;
	return new Promise((resolve, reject) => {
		if (cache == true && $CACHE[config.url]) {
			resolve($CACHE[config.url]);
			return;
		} else if ($CACHE[config.url]) {
			delete $CACHE[config.url];
		}
		config.isLoading !== false && $loading.show();
		uni.request({
			...config,
			success(res) {
				console.log(res, 'crj')
				config.isLoading !== false && $loading.hide();
				let {
					code,
					message,
					result,
					data = result
				} = res.data;
				//console.log(code,'codef')
				if (config.isFilter === false) {
					resolve(res.data);
				} else if (code == 200) {
					if (cache == true) $CACHE[config.url] = data;
					resolve(data);
				} else if ([201].includes(code)) { //没有token或token失效
					toLogin().then(() => {
						config.header.token = uni.getStorageSync('token')
						uni.request({
							...config,
							success: (results) => {
								let {
									code,
									message,
									result,
									datas = result
								} = results.data;
								resolve(datas)
							}
						})
					})
				} else if (code == -40001) {

				} else {
					config.isError !== false && $msg.error(message);
					reject(res.data);
				}
			},
			fail(err) {
				config.isLoading !== false && $loading.hide();
				config.isError !== false && $msg.error('请求失败');
				reject(err);
			},
		})
	})
};

http.get = function(url, data, config = {}) {
	config.method = "GET";
	config.url = config.url || url;
	config.data = data;
	return http(config);
};
http.post = function(url, data, config = {}) {
	config.method = "POST";
	config.url = config.url || url;
	config.data = data;
	return http(config);
};
const toLogin = () => {
	return new Promise((resolve, reject) => {
		uni.login({
			provider: 'weixin', //使用微信登录
			onlyAuthorize: true,
			success: function(res) {
				console.log(res.code)
				http.post('login', {
					appId: getAppId(),
					code: res.code
				}).then(result => {
					console.log(result, 'result')
					uni.setStorageSync('token', result.token)
					http.get('userInfo').then(res2 => {
						resolve()
						uni.setStorageSync('userInfo', JSON.stringify(res2))
					})
				})
			}
		})
	})
}

export default {
	install(app, options) {
		app.config.globalProperties['$http'] = http;
		app.config.globalProperties['$msg'] = $msg;
		app.config.globalProperties['$loading'] = $loading;
	},
	$http: http,
	$msg,
	$api: $API,
	$loading,
	toLogin
}